<?php
class MY_Model extends Model
{
	public
		/*
		 * DB table fields
		 */
		$table = null,
		$prKey = null,
		
		/*
		 * validation fields
		 */
		$fields = array(),
		$rules = array(),
		
		$rowStatus = array(
			'1' => 'Активный',
			'2' => 'Неактивный',
		)		
	;

	function __construct()
	{
		parent::__construct();
	}

	function get($id = null)
	{
		$this->db->where($this->prKey, $id);
		$query = $this->db->get($this->table);
		
		return $query->row_array();
	}

	function getAll($order_by = null)
	{
		if (!empty($order_by))
		{
			$this->db->order_by($order_by);	
		}

		return $this->db->get($this->table);
	}
	
	function insert($data = array(), $get_id = true)
	{
		//TODO: last inserted ID
		$this->db->insert($this->table, $data);
		
		if ($get_id == true)
		{
			//return $this->db->insert_id();	
		}		
	}
	
	function update($data = array())
	{
		$this->db->where($this->prKey, $data[$this->prKey]);
		unset($data[$this->prKey]);
		$this->db->update($this->table, $data);
	}

	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$error = "";
		foreach ($items as $id)
		{	
			$res = $this->db->delete($this->table, array($this->prKey => $id));	
			
			if (is_null($res))
			{
				$error = true;
			}
		}
		return array("error" => $error);
	}
	
	function save($data)
	{
		if ($data[$this->prKey] > 0)
		{
			$this->update($data);
		}
		else
		{
			$this->insert($data);
		}
	}
	
	function getRules($ruleKeys = array())
	{
		$rules = array();
		
		foreach ($ruleKeys as $key)
		{
			if (!isset($this->rules[$key]))
			{
				die(sprintf('The rule key %s does not exist.', $key));
			}
			
			$rules[$key] = $this->rules[$key];
		}
		
		return $rules;
	}
	
	function getRowStatuses()
	{
		return $this->rowStatus;
	}
		
	function getArray($query)
	{
 		$array = array();
 		
 		foreach ($query->result('ARRAY') as $row)
 		{
 			$array[] = $row;
 		}
 		
 		return $array;
	}
	
	function getRowCount($sql = '')
	{
		if (empty($sql))
		{
			return false;
		}

		$sql = 'SELECT COUNT(*) AS count' . $sql;
		
		$r = $this->getArray($this->db->query($sql));

		return $r[0]['count'];
	}	
	
	function getByField($field = null, $value = null)
	{		
		if ($field)
		{
			$this->db->where($field, $value);
			$query = $this->db->get($this->table);	
		}
		
		if ($query->num_rows() === 1)
		{
			return $query->row_array();
		}
		
		return false;
	}
		
	function prepareRules($all_rules, $except_rules)
	{
		$rules = array();

		if (empty($except_rules))
		{
			return $all_rules;
		}
		
		if (!empty($all_rules))
		{
			foreach ($all_rules as $key => $item)
			{
				if (!in_array($key, $except_rules)) 
				{
					$rules[] = $key;	
				}
			}
			return $rules;
		}
	}	
}
?>